import React, { useState, useEffect, useCallback } from 'react';
import { Table, Button, message, Card, Space, Tag, Input, Modal, Popconfirm } from 'antd';
import { LoadingOutlined, SearchOutlined } from '@ant-design/icons';
import axios from 'axios';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';

interface Club {
  id: number;
  name: string;
  description: string;
  type: string;
  president: string;
  created_at: string;
  status: string | null;
}

interface ApiResponse<T> {
  success: boolean;
  data: T;
  message?: string;
}

const MyClub: React.FC = () => {
  const [clubs, setClubs] = useState<Club[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const fetchClubs = useCallback(async () => {
    setLoading(true);
    try {
      const userInfo = localStorage.getItem('userInfo');
      if (!userInfo) {
        message.error('请先登录');
        return;
      }

      const studentInfo = JSON.parse(userInfo);
      const studentId = studentInfo.id;

      // Fetch the club ids with "approved" status
      const statusResponse = await axios.get<ApiResponse<any[]>>(
        `http://localhost:5000/api/studentClubs/status/approved/student/${studentId}`
      );
      if (!statusResponse.data.success) {
        message.error('获取已加入社团失败');
        return;
      }

      const approvedClubIds = statusResponse.data.data.map((item) => item.club_id);

      // Fetch the details of clubs using the club_id values
      const clubPromises = approvedClubIds.map((clubId) =>
        axios.get<ApiResponse<Club>>(`http://localhost:5000/api/club/${clubId}`)
      );
      const clubResponses = await Promise.all(clubPromises);

      const clubsData = clubResponses.map((response) => response.data.data);
      setClubs(clubsData);

      setPagination((prev) => ({
        ...prev,
        total: clubsData.length,
      }));
    } catch (error) {
      console.error('获取已加入社团失败:', error);
      message.error('获取已加入社团失败');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchClubs();
  }, [fetchClubs]);

  const columns: ColumnsType<Club> = [
    {
      title: '社团ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      align: 'center',
    },
    {
      title: '社团名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '社团描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '负责人',
      dataIndex: 'president',
      key: 'president',
      width: 120,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 150,
      render: (date: string) => new Date(date).toLocaleDateString(),
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => (
        <Popconfirm
          title={`确定要退出社团 "${record.name}" 吗？`}
          okText="退出"
          okType="danger"
          cancelText="取消"
          onConfirm={() => {
            const userInfo = localStorage.getItem('userInfo');
            if (!userInfo) {
              message.error('请先登录');
              return;
            }
            
            const studentInfo = JSON.parse(userInfo);
            const studentId = studentInfo.id;
            
            axios.delete('http://localhost:5000/api/delectSClub', {
              data: {
                student_id: studentId,
                club_id: record.id
              }
            }).then(response => {
              if (response.status === 200) {
                message.success('成功退出社团');
                fetchClubs(); // 重新加载数据
              } else {
                message.error('退出社团失败');
              }
            }).catch(error => {
              console.error('退出社团出错:', error);
              message.error('退出社团失败，请稍后重试');
            });
          }}
        >
          <Button 
            type="link" 
            danger 
            size="small"
          >
            退出社团
          </Button>
        </Popconfirm>
      ),
    },
  ];

  return (
    <Card title="我的社团" bordered>
      <Table<Club>
        columns={columns}
        dataSource={clubs}
        rowKey="id"
        loading={{
          spinning: loading,
          indicator: <LoadingOutlined style={{ fontSize: 24 }} spin />,
        }}
        pagination={{
          ...pagination,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条`,
        }}
        bordered
        scroll={{ x: 'max-content' }}
      />
    </Card>
  );
};

export default MyClub;
